package fsu.cs.cis5930;

import java.util.Timer;
import java.util.TimerTask;

import fsu.cs.cis5930.Connection.Messages;
import fsu.cs.cis5930.Connection.Type;
import fsu.cs.cis5930.GameActivity.BombAdapter;

import android.app.Application;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.widget.FrameLayout;

//Since GameEngine is an Application, we can refer to it from anywhere.
public class GameEngine extends Application{
	
	/** Stores the connection state of the game. */
	private Connection gameConnection;
	
	/**Stores the settings of the game. */
	private Settings gameSettings;								
	
	private int score;
	
	/**
	 * Stores the game board.
	 */
	private BombAdapter gameBoard;
	
	private Handler endGame;

	@Override
	public void onCreate() {
		gameSettings = new Settings(this);
		gameBoard = null;
		gameConnection = null;
	};

	public Settings getSettings()
	{
		return gameSettings;
	}
	
	public void setGameBoard(BombAdapter i)
	{
		gameBoard = i;
	}
		
	public void createBomb(Bomb.Type bType)
	{
		gameBoard.createBomb( bType );
	}
	
	public void increaseScore()
	{
		score++;
	}
	
	public int getScore()
	{return score; }
	
	/**
	 * Sends a bomb. Calls the respective sendBomb function, depending on our connection type.
	 * @param bType
	 */
	void sendBomb(Bomb.Type bType)
	{
		gameConnection.sendMessage(Messages.SEND_BOMB, bType.ordinal());
		
	}
	
	
	/**
	 * Attempt to communicate with other devices. If we succeed, start game.
	 */
	public void connect()
	{
		Connection.Type connectionType = gameSettings.getConnectionType();
		if (connectionType == Type.SINGLE_PLAYER)
			return;
		
		gameConnection = new Connection( connectionType);
		
	}
	
	/**
	 * Run this when game begins to get everything set up, engine-wise.
	 */
	public void startGame()
	{
		score = 0;
	}
	
	/**
	 *  Run this when the game ends to do some clean up tasks.
	 */
	public void endGame()
	{
		endGame.sendEmptyMessage(0);
	}
	

	
	/**
	 * Layout in charge of holding one Bomb object. 
	 * Keeps track if there is a bomb in the current position.
	 *
	 */
	public static class BombSpace extends FrameLayout
	{
			private Bomb bomb;
		
		public BombSpace(Context context) {
			super(context);
			bomb = new Bomb(context, Bomb.Type.EMPTY);
			addView(bomb);
		}
		
	
		public void addView(Bomb child)
		{
			removeView(bomb);
			super.addView(child);
			bomb = child;
			
		}
		
		public Bomb getBomb()
		{
			return bomb;
		}
		
		
	}



	public void setEndGame(Handler endGameHandler) {
		endGame = endGameHandler;
		
	}
	


}
